// Early bootstrap to patch module resolution before loading the main bundle.
// Fixes runtime errors like:
//   Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './decode' is not defined by "exports" in entities/package.json
// Some third-party packages still require 'entities/decode' or 'entities/escape'.
// We intercept resolution to map them to the public exports provided by entities.

try {
  const fs = require('node:fs')
  const Module = require('node:module')
  const path = require('node:path')
  const originalResolveFilename = Module._resolveFilename

  Module._resolveFilename = function patchedResolve(request, parent, isMain, options) {
    if (request === 'entities/decode') {
      try {
        return require.resolve('entities/lib/decode.js')
      }
      catch {}
    }
    if (request === 'entities/escape') {
      try {
        return require.resolve('entities/lib/escape.js')
      }
      catch {}
    }
    // Prisma client: redirect relative '.prisma/client/*' to unpacked node_modules
    if (request && typeof request === 'string' && request.startsWith('.prisma/')) {
      try {
        const resBase = process.resourcesPath || process.cwd()
        const unpackedNodeModules = path.join(resBase, 'app.asar.unpacked', 'node_modules')
        // Prisma client generates files under @prisma/client/.prisma/**
        const clientRoot = path.join(unpackedNodeModules, '@prisma', 'client')
        const target = path.join(clientRoot, request) // e.g. .prisma/client/default -> @prisma/client/.prisma/client/default
        const withJs = fs.existsSync(target) ? target : (fs.existsSync(`${target}.js`) ? `${target}.js` : target)
        if (fs.existsSync(withJs))
          return withJs
      }
      catch {}
    }
    return originalResolveFilename.call(this, request, parent, isMain, options)
  }
}
catch {}

// Now load the actual Electron main bundle (built by electron-vite)
require('./out/main/index.js')
